package com.tanger.permission.permission.service.impl;

import com.tanger.common.result.ActionResult;
import com.tanger.permission.entity.role.EntityUserRole;
import com.tanger.permission.entity.vo.UserRoleVo;
import com.tanger.permission.mapper.role.UserRoleManualMapper;
import com.tanger.permission.mapper.role.UserRoleMapper;
import com.tanger.permission.permission.service.UserRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description 权限实现类
 * @Author Hchenbin
 * @Date 2022/6/29 15:01
 * @Version 1.0
 */
@Service
public class UserRoleServiceImpl implements UserRoleService{

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserRoleManualMapper manualMapper;
    private static Logger logger = LoggerFactory.getLogger(UserRoleServiceImpl.class);

    @Override
    public List<UserRoleVo> findAll(Long userId) {
        return Optional.ofNullable(manualMapper.queryUserRoleByUserId(userId)).orElse(new ArrayList<>());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult saveUserRole(List<EntityUserRole> userRoles) {
        List<Long> userIds = userRoles.stream().map(EntityUserRole::getUserId).distinct().collect(Collectors.toList());
        manualMapper.deleteUSerRoleByUserId(userIds);
        userRoleMapper.batchInsert(userRoles);
        return ActionResult.buildResultSuccess();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult deleteUserRole(Long[] ids) {
        int count = userRoleMapper.deleteBatchIds(Arrays.asList(ids));
        return count == ids.length? ActionResult.buildResultSuccess():ActionResult.buildResultError("删除失败");
    }
}
